import { BezierPath } from '../parser/bezierPath';

export const enum LineCap {
  BUTT = "BUTT",
  ROUND = "ROUND",
  SQUARE = "SQUARE",
}

export const encodeLineCap: { [key: string]: number } = {
  BUTT: 0,
  ROUND: 1,
  SQUARE: 2,
};

export const decodeLineCap: { [key: number]: LineCap } = {
  0: LineCap.BUTT,
  1: LineCap.ROUND,
  2: LineCap.SQUARE,
};

export const enum LineJoin {
  MITER = "MITER",
  ROUND = "ROUND",
  BEVEL = "BEVEL",
}

export const encodeLineJoin: { [key: string]: number } = {
  MITER: 0,
  ROUND: 1,
  BEVEL: 2,
};

export const decodeLineJoin: { [key: number]: LineJoin } = {
  0: LineJoin.MITER,
  1: LineJoin.ROUND,
  2: LineJoin.BEVEL,
};

export const enum ShapeType {
  SHAPE = "SHAPE",
  RECT = "RECT",
  ELLIPSE = "ELLIPSE",
  KEEP = "KEEP",
}

export const encodeShapeType: { [key: string]: number } = {
  SHAPE: 0,
  RECT: 1,
  ELLIPSE: 2,
  KEEP: 3,
};

export const decodeShapeType: { [key: number]: ShapeType } = {
  0: ShapeType.SHAPE,
  1: ShapeType.RECT,
  2: ShapeType.ELLIPSE,
  3: ShapeType.KEEP,
};

export interface MovieParams {
  viewBoxWidth?: number;
  viewBoxHeight?: number;
  fps?: number;
  frames?: number;
}

export function encodeMovieParams(message: MovieParams): Uint8Array {
  let bb = popByteBuffer();
  _encodeMovieParams(message, bb);
  return toUint8Array(bb);
}

export function _encodeMovieParams(message: MovieParams, bb: ByteBuffer): void {
  // optional float viewBoxWidth = 1;
  let $viewBoxWidth = message.viewBoxWidth;
  if ($viewBoxWidth !== undefined) {
    writeVarint32(bb, 13);
    writeFloat(bb, $viewBoxWidth);
  }

  // optional float viewBoxHeight = 2;
  let $viewBoxHeight = message.viewBoxHeight;
  if ($viewBoxHeight !== undefined) {
    writeVarint32(bb, 21);
    writeFloat(bb, $viewBoxHeight);
  }

  // optional int32 fps = 3;
  let $fps = message.fps;
  if ($fps !== undefined) {
    writeVarint32(bb, 24);
    writeVarint64(bb, intToLong($fps));
  }

  // optional int32 frames = 4;
  let $frames = message.frames;
  if ($frames !== undefined) {
    writeVarint32(bb, 32);
    writeVarint64(bb, intToLong($frames));
  }
}

export function decodeMovieParams(binary: Uint8Array): MovieParams {
  return _decodeMovieParams(wrapByteBuffer(binary));
}

export function _decodeMovieParams(bb: ByteBuffer): MovieParams {
  let message: MovieParams = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional float viewBoxWidth = 1;
      case 1: {
        message.viewBoxWidth = readFloat(bb);
        break;
      }

    // optional float viewBoxHeight = 2;
      case 2: {
        message.viewBoxHeight = readFloat(bb);
        break;
      }

    // optional int32 fps = 3;
      case 3: {
        message.fps = readVarint32(bb);
        break;
      }

    // optional int32 frames = 4;
      case 4: {
        message.frames = readVarint32(bb);
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface SpriteEntity {
  imageKey?: string;
  frames?: FrameEntity[];
  matteKey?: string;
}

export function encodeSpriteEntity(message: SpriteEntity): Uint8Array {
  let bb = popByteBuffer();
  _encodeSpriteEntity(message, bb);
  return toUint8Array(bb);
}

export function _encodeSpriteEntity(message: SpriteEntity, bb: ByteBuffer): void {
  // optional string imageKey = 1;
  let $imageKey = message.imageKey;
  if ($imageKey !== undefined) {
    writeVarint32(bb, 10);
    writeString(bb, $imageKey);
  }

  // repeated FrameEntity frames = 2;
  let array$frames = message.frames;
  if (array$frames !== undefined) {
    for (let value of array$frames) {
      writeVarint32(bb, 18);
      let nested = popByteBuffer();
      _encodeFrameEntity(value, nested);
      writeVarint32(bb, nested.limit);
      writeByteBuffer(bb, nested);
      pushByteBuffer(nested);
    }
  }

  // optional string matteKey = 3;
  let $matteKey = message.matteKey;
  if ($matteKey !== undefined) {
    writeVarint32(bb, 26);
    writeString(bb, $matteKey);
  }
}

export function decodeSpriteEntity(binary: Uint8Array): SpriteEntity {
  return _decodeSpriteEntity(wrapByteBuffer(binary));
}

export function _decodeSpriteEntity(bb: ByteBuffer): SpriteEntity {
  let message: SpriteEntity = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional string imageKey = 1;
      case 1: {
        message.imageKey = readString(bb, readVarint32(bb));
        break;
      }

    // repeated FrameEntity frames = 2;
      case 2: {
        let limit = pushTemporaryLength(bb);
        let values = message.frames || (message.frames = []);
        values.push(_decodeFrameEntity(bb));
        bb.limit = limit;
        break;
      }

    // optional string matteKey = 3;
      case 3: {
        message.matteKey = readString(bb, readVarint32(bb));
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface AudioEntity {
  audioKey?: string;
  startFrame?: number;
  endFrame?: number;
  startTime?: number;
  totalTime?: number;
}

export function encodeAudioEntity(message: AudioEntity): Uint8Array {
  let bb = popByteBuffer();
  _encodeAudioEntity(message, bb);
  return toUint8Array(bb);
}

export function _encodeAudioEntity(message: AudioEntity, bb: ByteBuffer): void {
  // optional string audioKey = 1;
  let $audioKey = message.audioKey;
  if ($audioKey !== undefined) {
    writeVarint32(bb, 10);
    writeString(bb, $audioKey);
  }

  // optional int32 startFrame = 2;
  let $startFrame = message.startFrame;
  if ($startFrame !== undefined) {
    writeVarint32(bb, 16);
    writeVarint64(bb, intToLong($startFrame));
  }

  // optional int32 endFrame = 3;
  let $endFrame = message.endFrame;
  if ($endFrame !== undefined) {
    writeVarint32(bb, 24);
    writeVarint64(bb, intToLong($endFrame));
  }

  // optional int32 startTime = 4;
  let $startTime = message.startTime;
  if ($startTime !== undefined) {
    writeVarint32(bb, 32);
    writeVarint64(bb, intToLong($startTime));
  }

  // optional int32 totalTime = 5;
  let $totalTime = message.totalTime;
  if ($totalTime !== undefined) {
    writeVarint32(bb, 40);
    writeVarint64(bb, intToLong($totalTime));
  }
}

export function decodeAudioEntity(binary: Uint8Array): AudioEntity {
  return _decodeAudioEntity(wrapByteBuffer(binary));
}

export function _decodeAudioEntity(bb: ByteBuffer): AudioEntity {
  let message: AudioEntity = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional string audioKey = 1;
      case 1: {
        message.audioKey = readString(bb, readVarint32(bb));
        break;
      }

    // optional int32 startFrame = 2;
      case 2: {
        message.startFrame = readVarint32(bb);
        break;
      }

    // optional int32 endFrame = 3;
      case 3: {
        message.endFrame = readVarint32(bb);
        break;
      }

    // optional int32 startTime = 4;
      case 4: {
        message.startTime = readVarint32(bb);
        break;
      }

    // optional int32 totalTime = 5;
      case 5: {
        message.totalTime = readVarint32(bb);
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface Layout {
  x?: number;
  y?: number;
  width?: number;
  height?: number;
}

export function encodeLayout(message: Layout): Uint8Array {
  let bb = popByteBuffer();
  _encodeLayout(message, bb);
  return toUint8Array(bb);
}

export function _encodeLayout(message: Layout, bb: ByteBuffer): void {
  // optional float x = 1;
  let $x = message.x;
  if ($x !== undefined) {
    writeVarint32(bb, 13);
    writeFloat(bb, $x);
  }

  // optional float y = 2;
  let $y = message.y;
  if ($y !== undefined) {
    writeVarint32(bb, 21);
    writeFloat(bb, $y);
  }

  // optional float width = 3;
  let $width = message.width;
  if ($width !== undefined) {
    writeVarint32(bb, 29);
    writeFloat(bb, $width);
  }

  // optional float height = 4;
  let $height = message.height;
  if ($height !== undefined) {
    writeVarint32(bb, 37);
    writeFloat(bb, $height);
  }
}

export function decodeLayout(binary: Uint8Array): Layout {
  return _decodeLayout(wrapByteBuffer(binary));
}

export function _decodeLayout(bb: ByteBuffer): Layout {
  let message: Layout = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional float x = 1;
      case 1: {
        message.x = readFloat(bb);
        break;
      }

    // optional float y = 2;
      case 2: {
        message.y = readFloat(bb);
        break;
      }

    // optional float width = 3;
      case 3: {
        message.width = readFloat(bb);
        break;
      }

    // optional float height = 4;
      case 4: {
        message.height = readFloat(bb);
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface Transform {
  a?: number;
  b?: number;
  c?: number;
  d?: number;
  tx?: number;
  ty?: number;
}

export function encodeTransform(message: Transform): Uint8Array {
  let bb = popByteBuffer();
  _encodeTransform(message, bb);
  return toUint8Array(bb);
}

export function _encodeTransform(message: Transform, bb: ByteBuffer): void {
  // optional float a = 1;
  let $a = message.a;
  if ($a !== undefined) {
    writeVarint32(bb, 13);
    writeFloat(bb, $a);
  }

  // optional float b = 2;
  let $b = message.b;
  if ($b !== undefined) {
    writeVarint32(bb, 21);
    writeFloat(bb, $b);
  }

  // optional float c = 3;
  let $c = message.c;
  if ($c !== undefined) {
    writeVarint32(bb, 29);
    writeFloat(bb, $c);
  }

  // optional float d = 4;
  let $d = message.d;
  if ($d !== undefined) {
    writeVarint32(bb, 37);
    writeFloat(bb, $d);
  }

  // optional float tx = 5;
  let $tx = message.tx;
  if ($tx !== undefined) {
    writeVarint32(bb, 45);
    writeFloat(bb, $tx);
  }

  // optional float ty = 6;
  let $ty = message.ty;
  if ($ty !== undefined) {
    writeVarint32(bb, 53);
    writeFloat(bb, $ty);
  }
}

export function decodeTransform(binary: Uint8Array): Transform {
  return _decodeTransform(wrapByteBuffer(binary));
}

export function _decodeTransform(bb: ByteBuffer): Transform {
  let message: Transform = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional float a = 1;
      case 1: {
        message.a = readFloat(bb);
        break;
      }

    // optional float b = 2;
      case 2: {
        message.b = readFloat(bb);
        break;
      }

    // optional float c = 3;
      case 3: {
        message.c = readFloat(bb);
        break;
      }

    // optional float d = 4;
      case 4: {
        message.d = readFloat(bb);
        break;
      }

    // optional float tx = 5;
      case 5: {
        message.tx = readFloat(bb);
        break;
      }

    // optional float ty = 6;
      case 6: {
        message.ty = readFloat(bb);
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface ShapeArgs {
  d?: string;
}

export function encodeShapeArgs(message: ShapeArgs): Uint8Array {
  let bb = popByteBuffer();
  _encodeShapeArgs(message, bb);
  return toUint8Array(bb);
}

export function _encodeShapeArgs(message: ShapeArgs, bb: ByteBuffer): void {
  // optional string d = 1;
  let $d = message.d;
  if ($d !== undefined) {
    writeVarint32(bb, 10);
    writeString(bb, $d);
  }
}

export function decodeShapeArgs(binary: Uint8Array): ShapeArgs {
  return _decodeShapeArgs(wrapByteBuffer(binary));
}

export function _decodeShapeArgs(bb: ByteBuffer): ShapeArgs {
  let message: ShapeArgs = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional string d = 1;
      case 1: {
        message.d = readString(bb, readVarint32(bb));
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface RectArgs {
  x?: number;
  y?: number;
  width?: number;
  height?: number;
  cornerRadius?: number;
}

export function encodeRectArgs(message: RectArgs): Uint8Array {
  let bb = popByteBuffer();
  _encodeRectArgs(message, bb);
  return toUint8Array(bb);
}

export function _encodeRectArgs(message: RectArgs, bb: ByteBuffer): void {
  // optional float x = 1;
  let $x = message.x;
  if ($x !== undefined) {
    writeVarint32(bb, 13);
    writeFloat(bb, $x);
  }

  // optional float y = 2;
  let $y = message.y;
  if ($y !== undefined) {
    writeVarint32(bb, 21);
    writeFloat(bb, $y);
  }

  // optional float width = 3;
  let $width = message.width;
  if ($width !== undefined) {
    writeVarint32(bb, 29);
    writeFloat(bb, $width);
  }

  // optional float height = 4;
  let $height = message.height;
  if ($height !== undefined) {
    writeVarint32(bb, 37);
    writeFloat(bb, $height);
  }

  // optional float cornerRadius = 5;
  let $cornerRadius = message.cornerRadius;
  if ($cornerRadius !== undefined) {
    writeVarint32(bb, 45);
    writeFloat(bb, $cornerRadius);
  }
}

export function decodeRectArgs(binary: Uint8Array): RectArgs {
  return _decodeRectArgs(wrapByteBuffer(binary));
}

export function _decodeRectArgs(bb: ByteBuffer): RectArgs {
  let message: RectArgs = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional float x = 1;
      case 1: {
        message.x = readFloat(bb);
        break;
      }

    // optional float y = 2;
      case 2: {
        message.y = readFloat(bb);
        break;
      }

    // optional float width = 3;
      case 3: {
        message.width = readFloat(bb);
        break;
      }

    // optional float height = 4;
      case 4: {
        message.height = readFloat(bb);
        break;
      }

    // optional float cornerRadius = 5;
      case 5: {
        message.cornerRadius = readFloat(bb);
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface EllipseArgs {
  x?: number;
  y?: number;
  radiusX?: number;
  radiusY?: number;
}

export function encodeEllipseArgs(message: EllipseArgs): Uint8Array {
  let bb = popByteBuffer();
  _encodeEllipseArgs(message, bb);
  return toUint8Array(bb);
}

export function _encodeEllipseArgs(message: EllipseArgs, bb: ByteBuffer): void {
  // optional float x = 1;
  let $x = message.x;
  if ($x !== undefined) {
    writeVarint32(bb, 13);
    writeFloat(bb, $x);
  }

  // optional float y = 2;
  let $y = message.y;
  if ($y !== undefined) {
    writeVarint32(bb, 21);
    writeFloat(bb, $y);
  }

  // optional float radiusX = 3;
  let $radiusX = message.radiusX;
  if ($radiusX !== undefined) {
    writeVarint32(bb, 29);
    writeFloat(bb, $radiusX);
  }

  // optional float radiusY = 4;
  let $radiusY = message.radiusY;
  if ($radiusY !== undefined) {
    writeVarint32(bb, 37);
    writeFloat(bb, $radiusY);
  }
}

export function decodeEllipseArgs(binary: Uint8Array): EllipseArgs {
  return _decodeEllipseArgs(wrapByteBuffer(binary));
}

export function _decodeEllipseArgs(bb: ByteBuffer): EllipseArgs {
  let message: EllipseArgs = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional float x = 1;
      case 1: {
        message.x = readFloat(bb);
        break;
      }

    // optional float y = 2;
      case 2: {
        message.y = readFloat(bb);
        break;
      }

    // optional float radiusX = 3;
      case 3: {
        message.radiusX = readFloat(bb);
        break;
      }

    // optional float radiusY = 4;
      case 4: {
        message.radiusY = readFloat(bb);
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface ShapeEntity {
  type?: ShapeType;
  shape?: ShapeArgs;
  rect?: RectArgs;
  ellipse?: EllipseArgs;
  styles?: ShapeStyle;
  transform?: Transform;
}

export function encodeShapeEntity(message: ShapeEntity): Uint8Array {
  let bb = popByteBuffer();
  _encodeShapeEntity(message, bb);
  return toUint8Array(bb);
}

export function _encodeShapeEntity(message: ShapeEntity, bb: ByteBuffer): void {
  // optional ShapeType type = 1;
  let $type = message.type;
  if ($type !== undefined) {
    writeVarint32(bb, 8);
    writeVarint32(bb, encodeShapeType[$type]);
  }

  // optional ShapeArgs shape = 2;
  let $shape = message.shape;
  if ($shape !== undefined) {
    writeVarint32(bb, 18);
    let nested = popByteBuffer();
    _encodeShapeArgs($shape, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional RectArgs rect = 3;
  let $rect = message.rect;
  if ($rect !== undefined) {
    writeVarint32(bb, 26);
    let nested = popByteBuffer();
    _encodeRectArgs($rect, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional EllipseArgs ellipse = 4;
  let $ellipse = message.ellipse;
  if ($ellipse !== undefined) {
    writeVarint32(bb, 34);
    let nested = popByteBuffer();
    _encodeEllipseArgs($ellipse, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional ShapeStyle styles = 10;
  let $styles = message.styles;
  if ($styles !== undefined) {
    writeVarint32(bb, 82);
    let nested = popByteBuffer();
    _encodeShapeStyle($styles, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional Transform transform = 11;
  let $transform = message.transform;
  if ($transform !== undefined) {
    writeVarint32(bb, 90);
    let nested = popByteBuffer();
    _encodeTransform($transform, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }
}

export function decodeShapeEntity(binary: Uint8Array): ShapeEntity {
  return _decodeShapeEntity(wrapByteBuffer(binary));
}

export function _decodeShapeEntity(bb: ByteBuffer): ShapeEntity {
  let message: ShapeEntity = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional ShapeType type = 1;
      case 1: {
        message.type = decodeShapeType[readVarint32(bb)];
        break;
      }

    // optional ShapeArgs shape = 2;
      case 2: {
        let limit = pushTemporaryLength(bb);
        message.shape = _decodeShapeArgs(bb);
        bb.limit = limit;
        break;
      }

    // optional RectArgs rect = 3;
      case 3: {
        let limit = pushTemporaryLength(bb);
        message.rect = _decodeRectArgs(bb);
        bb.limit = limit;
        break;
      }

    // optional EllipseArgs ellipse = 4;
      case 4: {
        let limit = pushTemporaryLength(bb);
        message.ellipse = _decodeEllipseArgs(bb);
        bb.limit = limit;
        break;
      }

    // optional ShapeStyle styles = 10;
      case 10: {
        let limit = pushTemporaryLength(bb);
        message.styles = _decodeShapeStyle(bb);
        bb.limit = limit;
        break;
      }

    // optional Transform transform = 11;
      case 11: {
        let limit = pushTemporaryLength(bb);
        message.transform = _decodeTransform(bb);
        bb.limit = limit;
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface RGBAColor {
  r?: number;
  g?: number;
  b?: number;
  a?: number;
}

export function encodeRGBAColor(message: RGBAColor): Uint8Array {
  let bb = popByteBuffer();
  _encodeRGBAColor(message, bb);
  return toUint8Array(bb);
}

export function _encodeRGBAColor(message: RGBAColor, bb: ByteBuffer): void {
  // optional float r = 1;
  let $r = message.r;
  if ($r !== undefined) {
    writeVarint32(bb, 13);
    writeFloat(bb, $r);
  }

  // optional float g = 2;
  let $g = message.g;
  if ($g !== undefined) {
    writeVarint32(bb, 21);
    writeFloat(bb, $g);
  }

  // optional float b = 3;
  let $b = message.b;
  if ($b !== undefined) {
    writeVarint32(bb, 29);
    writeFloat(bb, $b);
  }

  // optional float a = 4;
  let $a = message.a;
  if ($a !== undefined) {
    writeVarint32(bb, 37);
    writeFloat(bb, $a);
  }
}

export function decodeRGBAColor(binary: Uint8Array): RGBAColor {
  return _decodeRGBAColor(wrapByteBuffer(binary));
}

export function _decodeRGBAColor(bb: ByteBuffer): RGBAColor {
  let message: RGBAColor = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional float r = 1;
      case 1: {
        message.r = readFloat(bb);
        break;
      }

    // optional float g = 2;
      case 2: {
        message.g = readFloat(bb);
        break;
      }

    // optional float b = 3;
      case 3: {
        message.b = readFloat(bb);
        break;
      }

    // optional float a = 4;
      case 4: {
        message.a = readFloat(bb);
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface ShapeStyle {
  fill?: RGBAColor;
  stroke?: RGBAColor;
  strokeWidth?: number;
  lineCap?: LineCap;
  lineJoin?: LineJoin;
  miterLimit?: number;
  lineDashI?: number;
  lineDashII?: number;
  lineDashIII?: number;
}

export function encodeShapeStyle(message: ShapeStyle): Uint8Array {
  let bb = popByteBuffer();
  _encodeShapeStyle(message, bb);
  return toUint8Array(bb);
}

export function _encodeShapeStyle(message: ShapeStyle, bb: ByteBuffer): void {
  // optional RGBAColor fill = 1;
  let $fill = message.fill;
  if ($fill !== undefined) {
    writeVarint32(bb, 10);
    let nested = popByteBuffer();
    _encodeRGBAColor($fill, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional RGBAColor stroke = 2;
  let $stroke = message.stroke;
  if ($stroke !== undefined) {
    writeVarint32(bb, 18);
    let nested = popByteBuffer();
    _encodeRGBAColor($stroke, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional float strokeWidth = 3;
  let $strokeWidth = message.strokeWidth;
  if ($strokeWidth !== undefined) {
    writeVarint32(bb, 29);
    writeFloat(bb, $strokeWidth);
  }

  // optional LineCap lineCap = 4;
  let $lineCap = message.lineCap;
  if ($lineCap !== undefined) {
    writeVarint32(bb, 32);
    writeVarint32(bb, encodeLineCap[$lineCap]);
  }

  // optional LineJoin lineJoin = 5;
  let $lineJoin = message.lineJoin;
  if ($lineJoin !== undefined) {
    writeVarint32(bb, 40);
    writeVarint32(bb, encodeLineJoin[$lineJoin]);
  }

  // optional float miterLimit = 6;
  let $miterLimit = message.miterLimit;
  if ($miterLimit !== undefined) {
    writeVarint32(bb, 53);
    writeFloat(bb, $miterLimit);
  }

  // optional float lineDashI = 7;
  let $lineDashI = message.lineDashI;
  if ($lineDashI !== undefined) {
    writeVarint32(bb, 61);
    writeFloat(bb, $lineDashI);
  }

  // optional float lineDashII = 8;
  let $lineDashII = message.lineDashII;
  if ($lineDashII !== undefined) {
    writeVarint32(bb, 69);
    writeFloat(bb, $lineDashII);
  }

  // optional float lineDashIII = 9;
  let $lineDashIII = message.lineDashIII;
  if ($lineDashIII !== undefined) {
    writeVarint32(bb, 77);
    writeFloat(bb, $lineDashIII);
  }
}

export function decodeShapeStyle(binary: Uint8Array): ShapeStyle {
  return _decodeShapeStyle(wrapByteBuffer(binary));
}

export function _decodeShapeStyle(bb: ByteBuffer): ShapeStyle {
  let message: ShapeStyle = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional RGBAColor fill = 1;
      case 1: {
        let limit = pushTemporaryLength(bb);
        message.fill = _decodeRGBAColor(bb);
        bb.limit = limit;
        break;
      }

    // optional RGBAColor stroke = 2;
      case 2: {
        let limit = pushTemporaryLength(bb);
        message.stroke = _decodeRGBAColor(bb);
        bb.limit = limit;
        break;
      }

    // optional float strokeWidth = 3;
      case 3: {
        message.strokeWidth = readFloat(bb);
        break;
      }

    // optional LineCap lineCap = 4;
      case 4: {
        message.lineCap = decodeLineCap[readVarint32(bb)];
        break;
      }

    // optional LineJoin lineJoin = 5;
      case 5: {
        message.lineJoin = decodeLineJoin[readVarint32(bb)];
        break;
      }

    // optional float miterLimit = 6;
      case 6: {
        message.miterLimit = readFloat(bb);
        break;
      }

    // optional float lineDashI = 7;
      case 7: {
        message.lineDashI = readFloat(bb);
        break;
      }

    // optional float lineDashII = 8;
      case 8: {
        message.lineDashII = readFloat(bb);
        break;
      }

    // optional float lineDashIII = 9;
      case 9: {
        message.lineDashIII = readFloat(bb);
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface FrameEntity {
  alpha?: number;
  layout?: Layout;
  transform?: Transform;
  clipPath?: string;
  shapes?: ShapeEntity[];
  maskPath?: BezierPath;
  lastShapes: ShapeEntity[];
  nx?: number;
  ny?: number;
}

export function encodeFrameEntity(message: FrameEntity): Uint8Array {
  let bb = popByteBuffer();
  _encodeFrameEntity(message, bb);
  return toUint8Array(bb);
}

export function _encodeFrameEntity(message: FrameEntity, bb: ByteBuffer): void {
  // optional float alpha = 1;
  let $alpha = message.alpha;
  if ($alpha !== undefined) {
    writeVarint32(bb, 13);
    writeFloat(bb, $alpha);
  }

  // optional Layout layout = 2;
  let $layout = message.layout;
  if ($layout !== undefined) {
    writeVarint32(bb, 18);
    let nested = popByteBuffer();
    _encodeLayout($layout, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional Transform transform = 3;
  let $transform = message.transform;
  if ($transform !== undefined) {
    writeVarint32(bb, 26);
    let nested = popByteBuffer();
    _encodeTransform($transform, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional string clipPath = 4;
  let $clipPath = message.clipPath;
  if ($clipPath !== undefined) {
    writeVarint32(bb, 34);
    writeString(bb, $clipPath);
  }

  // repeated ShapeEntity shapes = 5;
  let array$shapes = message.shapes;
  if (array$shapes !== undefined) {
    for (let value of array$shapes) {
      writeVarint32(bb, 42);
      let nested = popByteBuffer();
      _encodeShapeEntity(value, nested);
      writeVarint32(bb, nested.limit);
      writeByteBuffer(bb, nested);
      pushByteBuffer(nested);
    }
  }
}

export function decodeFrameEntity(binary: Uint8Array): FrameEntity {
  return _decodeFrameEntity(wrapByteBuffer(binary));
}

export function _decodeFrameEntity(bb: ByteBuffer): FrameEntity {
  let message: FrameEntity = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional float alpha = 1;
      case 1: {
        message.alpha = readFloat(bb);
        break;
      }

    // optional Layout layout = 2;
      case 2: {
        let limit = pushTemporaryLength(bb);
        message.layout = _decodeLayout(bb);
        // if (message.layout) {
        //   message.layout.x = parseFloat((message.layout.x || 0).toString())
        //   message.layout.y = parseFloat((message.layout.y || 0).toString())
        //   message.layout.width = parseFloat((message.layout.width || 0).toString())
        //   message.layout.height = parseFloat((message.layout.height || 0).toString())
        // }
        bb.limit = limit;
        break;
      }

    // optional Transform transform = 3;
      case 3: {
        let limit = pushTemporaryLength(bb);
        message.transform = _decodeTransform(bb);
        if (message.transform) {
          message.transform.a = parseFloat((message.transform.a || 1).toString());
          message.transform.b = parseFloat((message.transform.b || 0).toString());
          message.transform.c = parseFloat((message.transform.c || 0).toString());
          message.transform.d = parseFloat((message.transform.d || 1).toString());
          message.transform.tx = parseFloat((message.transform.tx || 0).toString());
          message.transform.ty = parseFloat((message.transform.ty || 0).toString());
        }
        bb.limit = limit;
        break;
      }

    // optional string clipPath = 4;
      case 4: {
        message.clipPath = readString(bb, readVarint32(bb));
        if (message.clipPath && message.clipPath.length > 0) {
          message.maskPath = new BezierPath(message.clipPath, undefined, {
            fill: {
              r: 0,
              g: 0,
              b: 0,
              a: 1
            }
          });
        }
        break;
      }

    // repeated ShapeEntity shapes = 5;
      case 5: {
        let limit = pushTemporaryLength(bb);
        let values = message.shapes || (message.shapes = []);
        values.push(_decodeShapeEntity(bb));
        // if (message.shapes) {
        //   if (message.shapes instanceof Array) {
        //     message.shapes.forEach(shape => {
        //       if (shape.styles) {
        //         if (shape.styles.fill) {
        //           if (typeof shape.styles.fill["r"] === "number") {
        //             shape.styles.fill[0] = shape.styles.fill["r"];
        //           }
        //           if (typeof shape.styles.fill["g"] === "number") {
        //             shape.styles.fill[1] = shape.styles.fill["g"];
        //           }
        //           if (typeof shape.styles.fill["b"] === "number") {
        //             shape.styles.fill[2] = shape.styles.fill["b"];
        //           }
        //           if (typeof shape.styles.fill["a"] === "number") {
        //             shape.styles.fill[3] = shape.styles.fill["a"];
        //           }
        //         }
        //         if (shape.styles.stroke) {
        //           if (typeof shape.styles.stroke["r"] === "number") {
        //             shape.styles.stroke[0] = shape.styles.stroke["r"];
        //           }
        //           if (typeof shape.styles.stroke["g"] === "number") {
        //             shape.styles.stroke[1] = shape.styles.stroke["g"];
        //           }
        //           if (typeof shape.styles.stroke["b"] === "number") {
        //             shape.styles.stroke[2] = shape.styles.stroke["b"];
        //           }
        //           if (typeof shape.styles.stroke["a"] === "number") {
        //             shape.styles.stroke[3] = shape.styles.stroke["a"];
        //           }
        //         }
        //       }
        //     })
        //   }
        //   if (message.shapes[0] && message.shapes[0].type === ShapeType.KEEP) {
        //     message.shapes = message.lastShapes;
        //   } else {
        //     message.shapes = message.shapes
        //     message.lastShapes = message.shapes;
        //   }
        // }
        // let llx =
        //   message.transform.a! * message.layout.x! + message.transform.c! * message.layout.y! + message.transform.tx!;
        // let lrx = message.transform.a! * (message.layout.x! + message.layout.width!) +
        //   message.transform.c! * message.layout.y! +
        //   message.transform.tx!;
        // let lbx = message.transform.a! * message.layout.x! +
        //   message.transform.c! * (message.layout.y! + message.layout.height!) +
        //   message.transform.tx!;
        // let rbx = message.transform.a! * (message.layout.x! + message.layout.width!) +
        //   message.transform.c! * (message.layout.y! + message.layout.height!) + message.transform.tx!;
        // let lly =
        //   message.transform.b! * message.layout.x! + message.transform.d! * message.layout.y! + message.transform.ty!;
        // let lry = message.transform.b! * (message.layout.x! + message.layout.width!) +
        //   message.transform.d! * message.layout.y! +
        //   message.transform.ty!;
        // let lby = message.transform.b! * message.layout.x! +
        //   message.transform.d! * (message.layout.y! + message.layout.height!) +
        //   message.transform.ty!;
        // let rby = message.transform.b! * (message.layout.x! + message.layout.width!) +
        //   message.transform.d! * (message.layout.y! + message.layout.height!) + message.transform.ty!;
        // message.nx = Math.min(Math.min(lbx, rbx), Math.min(llx, lrx));
        // message.ny = Math.min(Math.min(lby, rby), Math.min(lly, lry));
        bb.limit = limit;
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface MovieEntity {
  version?: string;
  params?: MovieParams;
  images?: Record<string, Uint8Array>;
  localImages?: Record<string, string>;
  sprites?: SpriteEntity[];
  audios?: AudioEntity[];
}

export function encodeMovieEntity(message: MovieEntity): Uint8Array {
  let bb = popByteBuffer();
  _encodeMovieEntity(message, bb);
  return toUint8Array(bb);
}

export function _encodeMovieEntity(message: MovieEntity, bb: ByteBuffer): void {
  // optional string version = 1;
  let $version = message.version;
  if ($version !== undefined) {
    writeVarint32(bb, 10);
    writeString(bb, $version);
  }

  // optional MovieParams params = 2;
  let $params = message.params;
  if ($params !== undefined) {
    writeVarint32(bb, 18);
    let nested = popByteBuffer();
    _encodeMovieParams($params, nested);
    writeVarint32(bb, nested.limit);
    writeByteBuffer(bb, nested);
    pushByteBuffer(nested);
  }

  // optional map<string, bytes> images = 3;
  let map$images = message.images;
  if (map$images !== undefined) {
    for (let key in map$images) {
      let nested = popByteBuffer();
      let value = map$images[key];
      writeVarint32(nested, 10);
      writeString(nested, key);
      writeVarint32(nested, 18);
      writeVarint32(nested, value.length), writeBytes(nested, value);
      writeVarint32(bb, 26);
      writeVarint32(bb, nested.offset);
      writeByteBuffer(bb, nested);
      pushByteBuffer(nested);
    }
  }

  // repeated SpriteEntity sprites = 4;
  let array$sprites = message.sprites;
  if (array$sprites !== undefined) {
    for (let value of array$sprites) {
      writeVarint32(bb, 34);
      let nested = popByteBuffer();
      _encodeSpriteEntity(value, nested);
      writeVarint32(bb, nested.limit);
      writeByteBuffer(bb, nested);
      pushByteBuffer(nested);
    }
  }

  // repeated AudioEntity audios = 5;
  let array$audios = message.audios;
  if (array$audios !== undefined) {
    for (let value of array$audios) {
      writeVarint32(bb, 42);
      let nested = popByteBuffer();
      _encodeAudioEntity(value, nested);
      writeVarint32(bb, nested.limit);
      writeByteBuffer(bb, nested);
      pushByteBuffer(nested);
    }
  }
}

export function decodeMovieEntity(binary: Uint8Array): MovieEntity {
  return _decodeMovieEntity(wrapByteBuffer(binary));
}

export function _decodeMovieEntity(bb: ByteBuffer): MovieEntity {
  let message: MovieEntity = {} as any;

  end_of_message: while (!isAtEnd(bb)) {
    let tag = readVarint32(bb);

    switch (tag >>> 3) {
      case 0:
        break end_of_message;

    // optional string version = 1;
      case 1: {
        message.version = readString(bb, readVarint32(bb));
        break;
      }

    // optional MovieParams params = 2;
      case 2: {
        let limit = pushTemporaryLength(bb);
        message.params = _decodeMovieParams(bb);
        bb.limit = limit;
        break;
      }

    // optional map<string, bytes> images = 3;
      case 3: {
        let values = message.images || (message.images = {});
        let outerLimit = pushTemporaryLength(bb);
        let key: string | undefined;
        let value: Uint8Array | undefined;
        end_of_entry: while (!isAtEnd(bb)) {
          let tag = readVarint32(bb);
          switch (tag >>> 3) {
            case 0:
              break end_of_entry;
            case 1: {
              key = readString(bb, readVarint32(bb));
              break;
            }
            case 2: {
              value = readBytes(bb, readVarint32(bb));
              break;
            }
            default:
              skipUnknownField(bb, tag & 7);
          }
        }
        if (key === undefined || value === undefined) {
          throw new Error("Invalid data for map: images");
        }
        values[key] = value;
        bb.limit = outerLimit;
        break;
      }

    // repeated SpriteEntity sprites = 4;
      case 4: {
        let limit = pushTemporaryLength(bb);
        let values = message.sprites || (message.sprites = []);
        values.push(_decodeSpriteEntity(bb));
        bb.limit = limit;
        break;
      }

    // repeated AudioEntity audios = 5;
      case 5: {
        let limit = pushTemporaryLength(bb);
        let values = message.audios || (message.audios = []);
        values.push(_decodeAudioEntity(bb));
        bb.limit = limit;
        break;
      }

      default:
        skipUnknownField(bb, tag & 7);
    }
  }

  return message;
}

export interface Long {
  low: number;
  high: number;
  unsigned: boolean;
}

interface ByteBuffer {
  bytes: Uint8Array;
  offset: number;
  limit: number;
}

function pushTemporaryLength(bb: ByteBuffer): number {
  let length = readVarint32(bb);
  let limit = bb.limit;
  bb.limit = bb.offset + length;
  return limit;
}

function skipUnknownField(bb: ByteBuffer, type: number): void {
  switch (type) {
    case 0:
      while (readByte(bb) & 0x80) {
      }
      break;
    case 2:
      skip(bb, readVarint32(bb));
      break;
    case 5:
      skip(bb, 4);
      break;
    case 1:
      skip(bb, 8);
      break;
    default:
      throw new Error("Unimplemented type: " + type);
  }
}

// The code below was modified from https://github.com/protobufjs/bytebuffer.js
// which is under the Apache License 2.0.

let f32 = new Float32Array(1);
let f32_u8 = new Uint8Array(f32.buffer);

let f64 = new Float64Array(1);
let f64_u8 = new Uint8Array(f64.buffer);

function intToLong(value: number): Long {
  value |= 0;
  return {
    low: value,
    high: value >> 31,
    unsigned: value >= 0,
  };
}

let bbStack: ByteBuffer[] = [];

function popByteBuffer(): ByteBuffer {
  const bb = bbStack.pop();
  if (!bb) {
    return { bytes: new Uint8Array(64), offset: 0, limit: 0 };
  }
  bb.offset = bb.limit = 0;
  return bb;
}

function pushByteBuffer(bb: ByteBuffer): void {
  bbStack.push(bb);
}

function wrapByteBuffer(bytes: Uint8Array): ByteBuffer {
  return { bytes, offset: 0, limit: bytes.length };
}

function toUint8Array(bb: ByteBuffer): Uint8Array {
  let bytes = bb.bytes;
  let limit = bb.limit;
  return bytes.length === limit ? bytes : bytes.subarray(0, limit);
}

function skip(bb: ByteBuffer, offset: number): void {
  if (bb.offset + offset > bb.limit) {
    throw new Error('Skip past limit');
  }
  bb.offset += offset;
}

function isAtEnd(bb: ByteBuffer): boolean {
  return bb.offset >= bb.limit;
}

function grow(bb: ByteBuffer, count: number): number {
  let bytes = bb.bytes;
  let offset = bb.offset;
  let limit = bb.limit;
  let finalOffset = offset + count;
  if (finalOffset > bytes.length) {
    let newBytes = new Uint8Array(finalOffset * 2);
    newBytes.set(bytes);
    bb.bytes = newBytes;
  }
  bb.offset = finalOffset;
  if (finalOffset > limit) {
    bb.limit = finalOffset;
  }
  return offset;
}

function advance(bb: ByteBuffer, count: number): number {
  let offset = bb.offset;
  if (offset + count > bb.limit) {
    throw new Error('Read past limit');
  }
  bb.offset += count;
  return offset;
}

function readBytes(bb: ByteBuffer, count: number): Uint8Array {
  let offset = advance(bb, count);
  return bb.bytes.subarray(offset, offset + count);
}

function writeBytes(bb: ByteBuffer, buffer: Uint8Array): void {
  let offset = grow(bb, buffer.length);
  bb.bytes.set(buffer, offset);
}

function readString(bb: ByteBuffer, count: number): string {
  // Sadly a hand-coded UTF8 decoder is much faster than subarray+TextDecoder in V8
  let offset = advance(bb, count);
  let fromCharCode = String.fromCharCode;
  let bytes = bb.bytes;
  let invalid = '\uFFFD';
  let text = '';

  for (let i = 0; i < count; i++) {
    let c1 = bytes[i + offset], c2: number, c3: number, c4: number, c: number;

    // 1 byte
    if ((c1 & 0x80) === 0) {
      text += fromCharCode(c1);
    }

    // 2 bytes
    else if ((c1 & 0xE0) === 0xC0) {
      if (i + 1 >= count) {
        text += invalid;
      } else {
        c2 = bytes[i + offset + 1];
        if ((c2 & 0xC0) !== 0x80) {
          text += invalid;
        } else {
          c = ((c1 & 0x1F) << 6) | (c2 & 0x3F);
          if (c < 0x80) {
            text += invalid;
          } else {
            text += fromCharCode(c);
            i++;
          }
        }
      }
    }

    // 3 bytes
    else if ((c1 & 0xF0) == 0xE0) {
      if (i + 2 >= count) {
        text += invalid;
      } else {
        c2 = bytes[i + offset + 1];
        c3 = bytes[i + offset + 2];
        if (((c2 | (c3 << 8)) & 0xC0C0) !== 0x8080) {
          text += invalid;
        } else {
          c = ((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F);
          if (c < 0x0800 || (c >= 0xD800 && c <= 0xDFFF)) {
            text += invalid;
          } else {
            text += fromCharCode(c);
            i += 2;
          }
        }
      }
    }

    // 4 bytes
    else if ((c1 & 0xF8) == 0xF0) {
      if (i + 3 >= count) {
        text += invalid;
      } else {
        c2 = bytes[i + offset + 1];
        c3 = bytes[i + offset + 2];
        c4 = bytes[i + offset + 3];
        if (((c2 | (c3 << 8) | (c4 << 16)) & 0xC0C0C0) !== 0x808080) {
          text += invalid;
        } else {
          c = ((c1 & 0x07) << 0x12) | ((c2 & 0x3F) << 0x0C) | ((c3 & 0x3F) << 0x06) | (c4 & 0x3F);
          if (c < 0x10000 || c > 0x10FFFF) {
            text += invalid;
          } else {
            c -= 0x10000;
            text += fromCharCode((c >> 10) + 0xD800, (c & 0x3FF) + 0xDC00);
            i += 3;
          }
        }
      }
    } else {
      text += invalid;
    }
  }

  return text;
}

function writeString(bb: ByteBuffer, text: string): void {
  // Sadly a hand-coded UTF8 encoder is much faster than TextEncoder+set in V8
  let n = text.length;
  let byteCount = 0;

  // Write the byte count first
  for (let i = 0; i < n; i++) {
    let c = text.charCodeAt(i);
    if (c >= 0xD800 && c <= 0xDBFF && i + 1 < n) {
      c = (c << 10) + text.charCodeAt(++i) - 0x35FDC00;
    }
    byteCount += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  }
  writeVarint32(bb, byteCount);

  let offset = grow(bb, byteCount);
  let bytes = bb.bytes;

  // Then write the bytes
  for (let i = 0; i < n; i++) {
    let c = text.charCodeAt(i);
    if (c >= 0xD800 && c <= 0xDBFF && i + 1 < n) {
      c = (c << 10) + text.charCodeAt(++i) - 0x35FDC00;
    }
    if (c < 0x80) {
      bytes[offset++] = c;
    } else {
      if (c < 0x800) {
        bytes[offset++] = ((c >> 6) & 0x1F) | 0xC0;
      } else {
        if (c < 0x10000) {
          bytes[offset++] = ((c >> 12) & 0x0F) | 0xE0;
        } else {
          bytes[offset++] = ((c >> 18) & 0x07) | 0xF0;
          bytes[offset++] = ((c >> 12) & 0x3F) | 0x80;
        }
        bytes[offset++] = ((c >> 6) & 0x3F) | 0x80;
      }
      bytes[offset++] = (c & 0x3F) | 0x80;
    }
  }
}

function writeByteBuffer(bb: ByteBuffer, buffer: ByteBuffer): void {
  let offset = grow(bb, buffer.limit);
  let from = bb.bytes;
  let to = buffer.bytes;

  // This for loop is much faster than subarray+set on V8
  for (let i = 0, n = buffer.limit; i < n; i++) {
    from[i + offset] = to[i];
  }
}

function readByte(bb: ByteBuffer): number {
  return bb.bytes[advance(bb, 1)];
}

function writeByte(bb: ByteBuffer, value: number): void {
  let offset = grow(bb, 1);
  bb.bytes[offset] = value;
}

function readFloat(bb: ByteBuffer): number {
  let offset = advance(bb, 4);
  let bytes = bb.bytes;

  // Manual copying is much faster than subarray+set in V8
  f32_u8[0] = bytes[offset++];
  f32_u8[1] = bytes[offset++];
  f32_u8[2] = bytes[offset++];
  f32_u8[3] = bytes[offset++];
  return f32[0];
}

function writeFloat(bb: ByteBuffer, value: number): void {
  let offset = grow(bb, 4);
  let bytes = bb.bytes;
  f32[0] = value;

  // Manual copying is much faster than subarray+set in V8
  bytes[offset++] = f32_u8[0];
  bytes[offset++] = f32_u8[1];
  bytes[offset++] = f32_u8[2];
  bytes[offset++] = f32_u8[3];
}

function readVarint32(bb: ByteBuffer): number {
  let c = 0;
  let value = 0;
  let b: number;
  do {
    b = readByte(bb);
    if (c < 32) {
      value |= (b & 0x7F) << c;
    }
    c += 7;
  } while (b & 0x80);
  return value;
}

function writeVarint32(bb: ByteBuffer, value: number): void {
  value >>>= 0;
  while (value >= 0x80) {
    writeByte(bb, (value & 0x7f) | 0x80);
    value >>>= 7;
  }
  writeByte(bb, value);
}

function writeVarint64(bb: ByteBuffer, value: Long): void {
  let part0 = value.low >>> 0;
  let part1 = ((value.low >>> 28) | (value.high << 4)) >>> 0;
  let part2 = value.high >>> 24;

  // ref: src/google/protobuf/io/coded_stream.cc
  let size =
    part2 === 0 ?
      part1 === 0 ?
        part0 < 1 << 14 ?
          part0 < 1 << 7 ? 1 : 2 :
          part0 < 1 << 21 ? 3 : 4 :
        part1 < 1 << 14 ?
          part1 < 1 << 7 ? 5 : 6 :
          part1 < 1 << 21 ? 7 : 8 :
      part2 < 1 << 7 ? 9 : 10;

  let offset = grow(bb, size);
  let bytes = bb.bytes;

  switch (size) {
    case 10:
      bytes[offset + 9] = (part2 >>> 7) & 0x01;
    case 9:
      bytes[offset + 8] = size !== 9 ? part2 | 0x80 : part2 & 0x7F;
    case 8:
      bytes[offset + 7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
    case 7:
      bytes[offset + 6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
    case 6:
      bytes[offset + 5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
    case 5:
      bytes[offset + 4] = size !== 5 ? part1 | 0x80 : part1 & 0x7F;
    case 4:
      bytes[offset + 3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
    case 3:
      bytes[offset + 2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
    case 2:
      bytes[offset + 1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
    case 1:
      bytes[offset] = size !== 1 ? part0 | 0x80 : part0 & 0x7F;
  }
}
